package pv.network;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import pv.finder.R;
import pv.util.CustomSimpleProgressDialog;
import pv.util.Utility;

import android.content.Context;
import android.os.AsyncTask;

public class BaseAsyncTask extends AsyncTask<String, Object, String> {

    protected CustomSimpleProgressDialog dialog;
    protected Context context;

    public BaseAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... urls) {

        return context.getString(R.string.TASK_SUCCESS);
    }

    protected void onPreExecute() {
        // dialog = new CustomProgressDialog(context, this);
        // dialog.showBox();
        showLoadingDialog();
    }

    protected void onPostExecute(String result) {
        dismissDialog();
        if (result.equals(context.getString(R.string.TASK_SUCCESS))) {
            doIfSuccess();
        } else if (result
                .equals(context.getString(R.string.TASK_ERROR_NETWORK))) {
            doIfErrorNetwork();
        } else if (result.equals(context.getString(R.string.TASK_ERROR_COMMON))) {
            doIfErrorCommon();
        } else {
            doIfReceiverFromServer(result);
        }

    }

    protected void showLoadingDialog() {

        // if (dialog == null)
        dialog = CustomSimpleProgressDialog.show(context, this);
        // if (!dialog.isShowing())
        // dialog.showBox();
    }

    protected void dismissDialog() {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
    }

    protected void doIfSuccess() {

    }

    protected void doIfErrorCommon() {
        Utility.showMessage(context,
                context.getString(R.string.MSG_ERROR_COMMON));
    }

    protected void doIfErrorNetwork() {
        Utility.showMessage(context,
                context.getString(R.string.MSG_ERROR_NETWORK));
    }

    protected void doIfReceiverFromServer(String receiver) {
        Utility.showMessage(context, receiver);
    }

    protected HttpEntity getEntity() throws UnsupportedEncodingException {
        // TODO Auto-generated method stub
        return null;
    }

    public class MyHttpMethod {
        protected String url;
        protected
        int responseCode = -1;
        protected int readTimeout = -1;


        public MyHttpMethod(String url) {
            this.url = url;
        }

        public String excute() throws IOException {
            return null;
        }

        public void setReadTimeOut(int readTimeout) {
            // TODO Auto-generated method stub
            this.readTimeout = readTimeout;

        }


        public int getResponseCode() {
            return responseCode;
        }
    }

    public class MyHttpGetMethod extends MyHttpMethod {
        public MyHttpGetMethod(String url) {
            super(url);
        }

        @Override
        public String excute() throws IOException {
            // TODO Auto-generated method stub

            // HttpClient client = NetworkHelper.createHttpClient();
            // HttpResponse response = client.execute(new HttpGet(url));
            // return NetworkHelper.convertToString(response);
            HttpURLConnection connection = NetworkHelper
                    .createHttpURLConnection(url);
            connection.setRequestMethod("GET");
            if (readTimeout != -1)
                connection.setReadTimeout(readTimeout);
            connection.setDoInput(true);
            connection.connect();

            BufferedInputStream in = new BufferedInputStream(
                    connection.getInputStream());
            String result = Utility.readStream(in);
            responseCode = connection.getResponseCode();
            connection.disconnect();

            return result;

        }

    }

    public class MyHttpPostMethod extends MyHttpMethod {
        List<NameValuePair> params;

        public MyHttpPostMethod(String url, List<NameValuePair> params) {
            super(url);
            // TODO Auto-generated constructor stub
            this.params = params;
        }

        @Override
        public String excute() throws IOException {
            // TODO Auto-generated method stub
            HttpURLConnection connection = NetworkHelper
                    .createHttpURLConnection(url);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            if (readTimeout != -1)
                connection.setReadTimeout(readTimeout);
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    os, "UTF-8"));
            writer.write(getQuery(params));
            writer.close();
            os.close();
            InputStream in = connection.getInputStream();
            String result = Utility.readStream(in);

            return result;

        }

        private String getQuery(List<NameValuePair> params)
                throws UnsupportedEncodingException {
            StringBuilder result = new StringBuilder();
            boolean first = true;

            for (NameValuePair pair : params) {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
            }

            return result.toString();
        }
    }

}
